package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddLink;
import com.itheima.ydd.service.IYddLinkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *     广告管理 - 友情链接
 * 前端控制器
 * </p>
 */
@Slf4j
@RestController
@RequestMapping("/ydd_link")
public class YddLinkController {
    @Autowired
    private IYddLinkService iYddLinkService;
    /**
     * 链接分页列表显示
     * @Param type 类型,1是文字类型,2图片类型
     * @Param page 页码数
     * @Param limit 每页数量
     * @return
     */
    @GetMapping("/list")
    public ResultData pageList(String type,String page,String limit){
        long page1 = Long.parseLong(page);
        long pageSize = Long.parseLong(limit);
        Page<YddLink> yddLinkPage = new Page(page1,pageSize);
        LambdaQueryWrapper<YddLink> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotEmpty(type),YddLink::getType,type);
        iYddLinkService.page(yddLinkPage,lqw);
        //将封装数据封装为pageResult
        return ResultData.ok("分页查询成功", PageResult.getPage(yddLinkPage));
    }

    /**
     * 新增链接
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody YddLink yddLink){
        log.info("新增链接:{}",yddLink.toString());
        boolean save = iYddLinkService.save(yddLink);
        if (save){
            return ResultData.ok("添加成功",yddLink);
        }
        return ResultData.error("添加失败");
    }

    /**
     * 删除链接信息
     */
    @GetMapping("/del")
    public ResultData delete(String id){
        if (StringUtils.isNotEmpty(id)){
            Long yddId = Long.parseLong(id);

            boolean flag = iYddLinkService.removeById(yddId);
            if (flag){
                return ResultData.ok("删除成功",null);
            }
        }
        return ResultData.error("删除失败");
    }

    /**
     * 根据id查询链接详情
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id){
        LambdaQueryWrapper<YddLink> lwq = new LambdaQueryWrapper<>();
        lwq.eq(YddLink::getId, Integer.parseInt(id));

        YddLink one = iYddLinkService.getOne(lwq);
        if (one != null){
            return ResultData.ok("查询详情成功",one);
        }
        return ResultData.error("查询详情失败");
    }

    /**
     * 修改链接信息
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddLink yddLink){
       if (yddLink != null){
           iYddLinkService.updateById(yddLink);
           return ResultData.ok("修改链接信息成功",yddLink);
       }
       return ResultData.error("修改失败");
    }
}
